package com.leyou.order.fifter;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.order.config.JwtProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:zty
 * @date: 2019年02月14日 16:56:53
 */
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private  JwtProperties props;

    //定义一个线程域 存放登录对象
    private static final ThreadLocal<UserInfo> th = new ThreadLocal<>();

    public  LoginInterceptor(){
        super();
    }

    public LoginInterceptor(JwtProperties props){
        this.props=props;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查询Token
        String token = CookieUtils.getCookieValue(request, props.getCookieName());
        if (StringUtils.isEmpty(token)){
            //用户未登录，返回401，拦截
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return  false;
        }
        //用户已登录，获取用户信息
        try{
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, props.getPublicKey());
            th.set(userInfo);
            return true;
        }catch (Exception e){
            //抛出异常，未登录
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //过滤器完成后，从线程域中删除用户信息
        th.remove();
    }
    public  static UserInfo getLoginUser(){
        return th.get();
    }
}
